﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using K9Nano.IM.Areas.Chat.Dto;
using K9Nano.IM.Areas.Chat.Services;
using K9Nano.IM.Caching;
using K9Nano.IM.Models;
using K9Nano.IM.ViewModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using WalkingTec.Mvvm.Core;

namespace K9Nano.IM.Areas.Chat.ViewModels.AccountVMs
{
    public class ChatLoginVM : AppMd5BaseVM
    {
        [Display(Name = "客户ID")]
        [Required(AllowEmptyStrings = false)]
        public string CustomerId { get; set; }

        [BindNever]
        public ChatApp ChatApp { get; set; }

        protected override void InitVM()
        {
            // 获取客户信息
            var user = GetUser();
            if (user == null) return;

            // 登录信息
            LoginUserInfo = new LoginUserInfo
            {
                Id = user.Id,
                ITCode = user.ITCode,
                Name = user.Name
            };
        }

        public override string GetFormatString()
        {
            return $"AppId={AppId}&CustomerId={CustomerId}&Timestamp={Timestamp}";
        }

        private ChatUser GetUser()
        {
            var chatCache = new ChatAppCache(this.Cache, DC);
            ChatApp = chatCache.Get(AppId);

            if (ChatApp == null)
            {
                this.MSD.AddModelError(nameof(AppId), "AppId不正确");
                return null;
            }

            if (CustomerId == Constants.Chat_Guest)
            {
                return ChatUser.Guest(AppId);
            }

            var user = DC.Set<User>()
                .FirstOrDefault(x => x.AppId == AppId
                                          && x.ExternalId == CustomerId);
            if (user == null)
            {
                var url = $"{ChatApp.CustomerInfoCallback}?id={CustomerId}";
                var httpClient = GlobalServices.GetService<AppHttpClient>();
                var appCustomer = httpClient.GetAsync<AppCustomer>(url).GetAwaiter().GetResult();
                if (appCustomer == null)
                {
                    this.DoLog($"获取外部客户信息失败，{url}", ActionLogTypesEnum.Exception);
                    return null;
                }

                user = new User
                {
                    ITCode = Guid.NewGuid().ToString(),
                    Password = Utils.GetMD5String(Guid.NewGuid().ToString()),
                    Name = appCustomer.Name,
                    IsValid = true,
                    AppId = AppId,
                    ExternalId = appCustomer.Id,
                    Nickname = appCustomer.Nickname,
                    Avatar = appCustomer.Avatar
                };

                DC.AddEntity(user);

                try
                {
                    DC.SaveChanges();
                }
                catch (Exception ex) when (ex.Message.Contains("idx_unique_app"))
                {
                    // ignore
                }
            }

            return new ChatUser(user);
        }

    }
}